package com.railway.switchs.action.business;

import com.railway.switchs.aspect.OperationLog;
import com.railway.switchs.base.BaseResponse;
import com.railway.switchs.constant.SystemConstant;
import com.railway.switchs.domain.dto.business.DeviceInfo;
import com.railway.switchs.domain.dto.business.SwitchInfo;
import com.railway.switchs.domain.query.business.SwitchInfoQuery;
import com.railway.switchs.enums.EnumReturnResult;
import com.railway.switchs.enums.EnumRunType;
import com.railway.switchs.service.business.IDeviceInfoService;
import com.railway.switchs.service.business.ISwitchInfoService;
import com.railway.switchs.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SwitchInfoAction
 * @Author 魏梓晟
 * @Version 1.0
 **/
@Controller
@Slf4j
@RequestMapping("/back/switchInfo")
public class SwitchInfoAction {

    @Autowired
    private ISwitchInfoService switchInfoService;

    @Autowired
    private IDeviceInfoService deviceInfoService;

    /**
     * 进入道岔信息列表
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(){
        return "switchInfo/list";
    }

    /**
     * 获取道岔信息数据
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getList",method = RequestMethod.POST)
    public SwitchInfoQuery getList(SwitchInfoQuery query) {
        try {
            query = switchInfoService.query(query);
            query.setCode(EnumReturnResult.RETURN_200.getCode());
        } catch (Exception e) {
            log.error("获取道岔信息列表数据异常", e);
            query.setCode(EnumReturnResult.RETURN_404.getCode());
            query.setMsg("获取道岔信息数据异常");
        }
        return query;
    }

    /**
     * 进入新增页面
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String preAdd(){
        return "switchInfo/add";
    }

    /**
     * 新增道岔信息
     * @param switchInfo
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="9",actionType ="0" )
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public BaseResponse add(@Validated SwitchInfo switchInfo, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("SwitchInfo-add参数有误");
                log.info("SwitchInfo-add参数有误："+result.getAllErrors().toString());
                return response;
            }
            switchInfo.setRunType(EnumRunType.UNUSED.getCode());
            switchInfoService.add(switchInfo);
            //选中的连接设备、交叉设备、组合设备设为已使用
            List<String> deviceCodeList = new ArrayList<>();
            deviceCodeList.add(switchInfo.getCombinationCode());
            deviceCodeList.add(switchInfo.getConnectCode());
            deviceCodeList.add(switchInfo.getCrossCode());
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setRunType(EnumRunType.USED.getCode());
            deviceInfo.setDeviceCodeList(deviceCodeList);
            deviceInfoService.editRunType(deviceInfo);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("新增成功");
        } catch (Exception e) {
            log.error("新增道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("新增失败");
        }
        return response;
    }

    /**
     * 进入修改界面
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public ModelAndView preEdit(Long id){
        ModelAndView mav = new ModelAndView();
        try{
            SwitchInfo switchInfo = switchInfoService.get(id);
            mav.addObject("switchInfo",switchInfo);
            mav.setViewName("switchInfo/edit");
        }catch (Exception e){
            log.error("获取道岔信息详情失败",e);
            mav.addObject(SystemConstant.ERROR_KEY,"系统异常");
            mav.setViewName("switchInfo/list");
        }
        return mav;
    }

    /**
     * 修改道岔信息
     * @param switchInfo
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="9",actionType ="1" )
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public BaseResponse edit(@Validated SwitchInfo switchInfo, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("SwitchInfo-edit参数有误");
                log.info("SwitchInfo-edit参数有误："+result.getAllErrors().toString());
                return response;
            }
            SwitchInfo switchInfoTemp = switchInfoService.get(switchInfo.getId());
            if(!EnumRunType.UNUSED.getCode().equals(switchInfoTemp.getRunType())){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("使用中的道岔信息不允许修改");
                return response;
            }
            switchInfoService.edit(switchInfo);

            //选中的连接设备、交叉设备、组合设备设为已使用
            List<String> deviceCodeList = new ArrayList<>();
            List<String> deviceCodeListTemp = new ArrayList<>();
            //修改组合编号
            if(StringUtil.isNotEmpty(switchInfo.getCombinationCode())){
                deviceCodeListTemp.add(switchInfoTemp.getCombinationCode());
                deviceCodeList.add(switchInfo.getCombinationCode());
            }
            if(StringUtil.isNotEmpty(switchInfo.getConnectCode())){
                deviceCodeListTemp.add(switchInfoTemp.getConnectCode());
                deviceCodeList.add(switchInfo.getConnectCode());
            }
            if(StringUtil.isNotEmpty(switchInfo.getCrossCode())){
                deviceCodeListTemp.add(switchInfoTemp.getCrossCode());
                deviceCodeList.add(switchInfo.getCrossCode());
            }
            if(StringUtil.isNotEmpty(deviceCodeList)){
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setRunType(EnumRunType.USED.getCode());
                deviceInfo.setDeviceCodeList(deviceCodeList);
                deviceInfoService.editRunType(deviceInfo);
            }
            if(StringUtil.isNotEmpty(deviceCodeListTemp)){
                DeviceInfo deviceInfoTemp = new DeviceInfo();
                deviceInfoTemp.setRunType(EnumRunType.UNUSED.getCode());
                deviceInfoTemp.setDeviceCodeList(deviceCodeListTemp);
                deviceInfoService.editRunType(deviceInfoTemp);
            }
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("修改成功");
        } catch (Exception e) {
            log.error("修改道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("修改失败");
        }
        return response;
    }

    /**
     * 删除道岔信息
     * @param id
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="9",actionType ="2" )
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public BaseResponse delete(Long id) {
        BaseResponse response = new BaseResponse();
        try {
            SwitchInfo switchInfo = switchInfoService.get(id);
            if(!EnumRunType.UNUSED.getCode().equals(switchInfo.getRunType())){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("使用中的道岔信息不允许删除");
                return response;
            }
            switchInfoService.delete(id);
            //删除道岔，则删除其连接设备、交叉设备、组合设备
            List<String> deviceCodeList = new ArrayList<>();
            deviceCodeList.add(switchInfo.getCombinationCode());
            deviceCodeList.add(switchInfo.getCrossCode());
            deviceCodeList.add(switchInfo.getConnectCode());
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceCodeList(deviceCodeList);
            deviceInfoService.deleteByCode(deviceInfo);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("删除道岔信息成功");
        } catch (Exception e) {
            log.error("删除道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("删除道岔信息失败");
        }
        return response;
    }

    /**
     * 获取道岔编号数据
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllList",method = RequestMethod.POST)
    public SwitchInfoQuery getAllList(SwitchInfoQuery query) {
        try {
            List<SwitchInfo> switchInfoList = switchInfoService.getList(query);
            if(StringUtil.isNotEmpty(query.getSwitchCodes())){
                String[] strs = query.getSwitchCodes().split(",");
                for(String str : strs){
                    SwitchInfoQuery queryTemp = new SwitchInfoQuery();
                    queryTemp.setSwitchCode(str);
                    List<SwitchInfo> switchInfoListTemp = switchInfoService.getList(queryTemp);
                    if(StringUtil.isNotEmpty(switchInfoListTemp)){
                        switchInfoList.addAll(switchInfoListTemp);
                    }
                }
            }
            query.setData(switchInfoList);
            query.setCode(EnumReturnResult.RETURN_200.getCode());
        } catch (Exception e) {
            log.error("获取道岔编号数据异常", e);
            query.setCode(EnumReturnResult.RETURN_404.getCode());
            query.setMsg("获取道岔编号编号异常");
        }
        return query;
    }

}
